<template>
  <el-dialog :title="title" v-model="visible" class="dialog-md" append-to-body @close="visible = false">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="85px" v-loading="loading">
      <el-row>
        <el-col :span="form.id ? 24 : 12">
          <el-form-item label="用户名称" prop="user_name">
            <el-input v-model="form.user_name" placeholder="请输入用户名称" maxlength="30" :disabled="!!form.id" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!form.id">
          <el-form-item label="用户密码" prop="password">
            <el-input
              v-model="form.password"
              placeholder="请输入用户密码"
              type="password"
              maxlength="20"
              show-password />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nick_name">
            <el-input v-model="form.nick_name" placeholder="请输入用户昵称" maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
              v-model="form.deptId"
              :data="deptOptions"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              value-key="id"
              placeholder="请选择归属部门"
              check-strictly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户性别" prop="sex">
            <el-select v-model="form.sex" placeholder="请选择">
              <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{
                dict.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位" prop="postIds">
            <el-select v-model="form.postIds" multiple placeholder="请选择">
              <el-option
                v-for="item in postOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="item.status !== '1'" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="roleIds">
            <el-select v-model="form.roleIds" multiple placeholder="请选择">
              <el-option
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="item.status !== '1'" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="头像" prop="avatar">
        <image-upload :default-list="defaultAvatar" v-model="form.avatar" :limit="1" over-hide-upload />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button class="medium" type="primary" :loading="submitting" :disabled="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button class="medium" @click="visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="AdminForm">
  import { infoAdminApi, editAdminApi, addAdminApi } from '@/api/system/admin'
  import { selectDeptApi } from '@/api/system/dept'
  import { selectRoleApi } from '@/api/system/role'
  import { selectPostApi } from '@/api/system/post'

  const props = defineProps({ row: Object, moduleName: String })
  const visible = defineModel()
  const { proxy } = getCurrentInstance()

  const formRef = useTemplateRef('formRef')
  const form = ref({
    user_name: undefined,
    nick_name: undefined,
    deptId: undefined,
    roleIds: [],
    postIds: [],
    phone: undefined,
    email: undefined,
    sex: undefined,
    status: '1',
    remark: undefined
  })

  const rules = computed(() => {
    const commonRules = {
      user_name: [
        { required: true, message: '用户名称不能为空', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
      ],
      nick_name: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
      status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
      deptId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
      email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
      phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
    }
    const addRules = {
      password: [
        { required: true, message: '用户密码不能为空', trigger: 'blur' },
        { min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间', trigger: 'blur' },
        { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
      ]
    }
    nextTick(() => {
      formRef.value?.clearValidate()
    })
    if (form.value.id) return commonRules
    return { ...commonRules, ...addRules }
  })

  const { sys_user_sex, sys_normal_disable } = proxy.useDict('sys_user_sex', 'sys_normal_disable')

  // 初始化加载
  const loading = ref(false)
  const title = ref('')
  onMounted(async () => {
    loading.value = true
    form.value.id = props.row?.id || undefined
    if (form.value.id) {
      title.value = '编辑' + props.moduleName
      await getRowData()
    } else {
      form.value.deptId = props.row?.deptId || undefined
      title.value = '添加' + props.moduleName
    }
    await getRoleOptions()
    await getPostOptions()
    await getDeptOptions()
    loading.value = false
  })

  // 提交按钮
  const submitting = ref(false)
  const emit = defineEmits(['submit'])
  async function handleSubmit() {
    try {
      const valid = await formRef.value.validate()
      if (!valid) return
    } catch (error) {
      return
    }
    if (submitting.value) return
    submitting.value = true
    try {
      if (form.value.id) {
        await editAdminApi(form.value)
      } else {
        await addAdminApi(form.value)
      }
      emit('submit')
      proxy.$modal.msgSuccess('操作成功')
      visible.value = false
    } catch (e) {
      submitting.value = false
    }
  }

  // 获取信息
  const defaultAvatar = ref('')
  async function getRowData() {
    try {
      const { info } = await infoAdminApi(form.value.id)
      form.value = proxy.dataToForm(form.value, info)
      defaultAvatar.value = info?.avatar || ''
    } catch (error) {
      visible.value = false
    }
  }

  const deptOptions = ref([])
  async function getDeptOptions() {
    try {
      const res = await selectDeptApi()
      deptOptions.value = proxy.listToTree(res?.list || [])
    } catch (e) {}
  }

  const postOptions = ref([])
  async function getPostOptions() {
    try {
      const res = await selectPostApi()
      postOptions.value = res?.list || []
    } catch (e) {}
  }

  const roleOptions = ref([])
  async function getRoleOptions() {
    try {
      const res = await selectRoleApi()
      roleOptions.value = res?.list || []
    } catch (e) {}
  }
</script>
